#include <concepts>
#include <coroutine>
#include <exception>
#include <iostream>
#include <chrono>
#include <thread>
using namespace std::chrono_literals;

struct ReturnObject
{
    struct promise_type
    {
        ReturnObject get_return_object()
        {
            return {
                .h_ = std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        std::suspend_never initial_suspend()
        {
            return {};
        }
        std::suspend_never final_suspend() noexcept
        {
            return {};
        }
        void unhandled_exception()
        {
        }
    };
    std::coroutine_handle<promise_type> h_;
    operator std::coroutine_handle<promise_type>() const
    {
        return h_;
    }
    operator std::coroutine_handle<>() const
    {
        return h_;
    }
};

[[nodiscard]] ReturnObject counter()
{
    for (size_t i = 0;; ++i)
    {
        std::cout << "Before co_await" << std::endl;
        co_await std::suspend_always{};
        std::cout << "Counter: " << i << std::endl;
    }
}

[[nodiscard]] ReturnObject hello()
{
    while (true)
    {
        std::cout << "Welcome\n";
        co_await std::suspend_always{};
        std::cout << "Hello\n";
        co_await std::suspend_always{};
        std::cout << "World\n";
        co_await std::suspend_always{};
        std::cout << "This\n";
        co_await std::suspend_always{};
        std::cout << "Is\n";
        co_await std::suspend_always{};
        std::cout << "C++20\n";
        co_await std::suspend_always{};
        std::cout << "Coroutine\n";
        co_await std::suspend_always{};
    }
}

void test1()
{
    // 初始化一个协程handle，赋予一个可调用对象counter
    // 并且立即suspend
    std::coroutine_handle<> h = counter();
    for (int i = 0; i < 3; ++i)
    {
        std::cout << "In test1()\n";
        std::cout << "Sleep 1s before calling h()\n";
        std::this_thread::sleep_for(1s);
        h();  //调用这个其实就是恢复到counter函数的co_await语句执行
    }
    h.destroy();
}

void test2()
{
    std::coroutine_handle<> h = hello();
    while (true)
    {
        h();
        std::this_thread::sleep_for(200ms);
    }
}

int main(int argc, char** argv)
{
    test1();
    test2();
    return 0;
}
